﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace PrgMonitor
{
	public class LogAPI
	{
		/// <summary>  
		/// 写入日志  
		/// </summary>  
		/// <param name="ex">日志信息</param>  
		public static void WriteLog(string ex)
		{
			if (!Directory.Exists("ExceptionLog"))
			{
				Directory.CreateDirectory("ExceptionLog");
			}

			while (true)
			{
				try
				{
					StreamWriter sw = new StreamWriter("ExceptionLog\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt", true, Encoding.GetEncoding("GB2312"));
					sw.Write(DateTime.Now.ToString("HH:mm:ss") + "  " + ex + "\r\n");
					sw.Close();
		
					break;
				}
				catch
				{
					System.Threading.Thread.Sleep(50);
					continue;
				}
			}
		}

		public static void WriteRunInfo(string ex, bool append)
		{
			if (!Directory.Exists("ExceptionLog"))
			{
				Directory.CreateDirectory("ExceptionLog");
			}

			while (true)
			{
				try
				{
					StreamWriter sw = new StreamWriter("ExceptionLog\\RunStatus.txt", append, Encoding.GetEncoding("GB2312"));
					sw.Write(ex + "\r\n");
					sw.Close();
					break;
				}
				catch
				{
					System.Threading.Thread.Sleep(50);
					continue;
				}
			}
		}

		public static int GetErrorCode(Exception ex)
		{
			var w32ex = ex as Win32Exception;
			if (w32ex == null)
			{
				w32ex = ex.InnerException as Win32Exception;
			}
			if (w32ex != null)
			{
				return w32ex.ErrorCode;
			}
			return 0;
		}
	}
}
